package cn.itcast.controller;


import cn.itcast.domain.User;
import cn.itcast.entity.ValidResult;
import cn.itcast.utils.validation.servicees.InsertGroup;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @PostMapping("/insert")
    @ResponseBody
    public ValidResult insert(@Validated(InsertGroup.class) User user, BindingResult bindingResult){
        ValidResult validationResult = new ValidResult();
        validate(bindingResult, validationResult);
        System.out.println(validationResult.toString());
        System.out.println(user);
        return validationResult;
    }

    private void validate(BindingResult bindingResult, ValidResult ValidResult) {
        if (bindingResult.hasErrors()){
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors){
                stringBuffer.append(objectError.getDefaultMessage() + "<br/>");
            }
            ValidResult.setMessage(stringBuffer.toString());
        }
    }

}
